package com.uenpay.im.ui.old.activity.red;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.qiyunxin.android.http.HttpInvokeResultCode;
import com.qiyunxin.android.http.utils.Utils;
import com.uenpay.im.IMApplication;
import com.uenpay.im.R;
import com.uenpay.im.ui.old.activity.chat.PickTalkActivity;
import com.uenpay.im.ui.old.activity.pwd.SetPayPwdActivity;
import com.uenpay.im.ui.old.activity.wallet.ChargeActivity;
import com.uenpay.im.ui.old.activity.wallet.WalletHandle;
import com.uenpay.im.callback.IOnBottomDialogListener;
import com.uenpay.im.entities.chatbean.MsgRedModel;
import com.uenpay.im.utilities.EditTextUtils;
import com.uenpay.im.weight.DialogUtility;
import com.uenpay.im.weight.PayPwdDialog;
import com.uenpay.util.app.base.BaseActivity;

import java.math.BigDecimal;

/**
 * @author SL
 * @created 2016-1-14 14:52:14
 * @copyRight http://www.qiyunxin.com
 * @function 发群聊红包
 */
public class SendRedToGroupActivity extends BaseActivity {

    private int red_type = 1;
    private Button send_btn;
    private EditText red_total_money_et, red_content_et, red_count_et;
    private TextView total_moeny_tv, red_status_tv, update_red_status_tv, red_total_tv;
    private String chat_id = "";
    private RedHandler mRedHandler = new RedHandler();
    private View loading;
    private double myBalance;
    private int haspaypassword;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isFullScreen = true;
        super.onCreate(savedInstanceState);
    }

    @Override
    public View bindView() {
        return null;
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_send_red_to_group_layout;
    }

    @Override
    public void initView(View view) {
        chat_id = getIntent().getStringExtra("chat_id");
        if (getIntent() != null && getIntent().hasExtra("redType")) {
            red_type = getIntent().getIntExtra("redType", 1);
        }
        initView();
        initListener();
        getMyBalance();
    }

    protected void initView() {
        ((TextView) findViewById(R.id.title_textview)).setText(getResources().getString(R.string.send_red));
        if (TextUtils.isEmpty(chat_id)) {
            if (red_type == 1) {
                ((TextView) findViewById(R.id.title_textview)).setText(getResources().getString(R.string.red_type_luck));
            } else {
                ((TextView) findViewById(R.id.title_textview)).setText(getResources().getString(R.string.red_type_ordinary));
            }
            findViewById(R.id.update_red_status_tv).setVisibility(View.GONE);
            findViewById(R.id.red_status_tv).setVisibility(View.GONE);
            findViewById(R.id.view).setVisibility(View.VISIBLE);
        }
        total_moeny_tv = (TextView) findViewById(R.id.total_moeny_tv);
        update_red_status_tv = (TextView) findViewById(R.id.update_red_status_tv);
        red_status_tv = (TextView) findViewById(R.id.red_status_tv);
        red_total_tv = (TextView) findViewById(R.id.red_total_tv);
        red_total_money_et = (EditText) findViewById(R.id.red_total_money_et);
        red_content_et = (EditText) findViewById(R.id.red_content_et);
        red_count_et = (EditText) findViewById(R.id.red_count_et);
        send_btn = (Button) findViewById(R.id.send_btn);
        loading = findViewById(R.id.loading);
    }

    protected void initListener() {
        findViewById(R.id.back_layout).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        red_count_et.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
                if (!TextUtils.isEmpty(arg0)) {
                    if (red_type == 2) {
                        setTotalMoney();
                    } else {
                        checkRecharge();
                    }
                } else {
                    total_moeny_tv.setText("¥0.00");
                }
                checkBtnStatus();
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
            }

            @Override
            public void afterTextChanged(Editable arg0) {
            }
        });
        red_total_money_et.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
                if (!TextUtils.isEmpty(arg0)) {
                    if (red_type == 2) {
                        setTotalMoney();
                    } else {
                        checkRecharge();
                    }

                } else {
                    total_moeny_tv.setText("¥0.00");
                }
                checkBtnStatus();
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
            }

            @Override
            public void afterTextChanged(Editable arg0) {
            }
        });

        red_content_et.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
                String content = red_content_et.getText().toString();
                if (Utils.String_length(content) > 50) {
                    if (content.length() > 25) {
                        red_content_et.setText(content.substring(0, 25));
                    }
                    return;
                }
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
            }

            @Override
            public void afterTextChanged(Editable arg0) {
            }
        });

        send_btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                String content = getResources().getString(R.string.red_default_content);
                String red_content = red_content_et.getText().toString();
                String red_count = red_count_et.getText().toString();
                if (!TextUtils.isEmpty(red_content)) {
                    content = red_content;
                }
                String total_money = red_total_money_et.getText().toString();
                if (!TextUtils.isEmpty(total_money) && !TextUtils.isEmpty(red_count)) {

                    double temp = Double.valueOf(total_money);
                    // if (temp > 10000) {
                    // showMoreDialog();
                    // } else {
                    if (temp > myBalance) {
                        showInsufficientBalanceDialog();
                    } else {
                        if (haspaypassword == 1) {
                            showPayPwdDialog(total_money, red_count, content);
                        } else {
                            showSetPwdDialog();
                            // createRed(total_money, red_count, content,"");
                        }
                    }
                    // }

                }
            }
        });
        update_red_status_tv.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                updateRedStatus();
            }
        });
    }

    // private void showMoreDialog() {
    // DialogUtility.showSingleBtnDialog(SendRedToGroupActivity.this,
    // R.string.crowdfund_max, R.string.comfirm, true,
    // new IOnBottomDialogListener() {
    //
    // @Override
    // public void onClicked() {
    //
    // }
    // });
    // }

    private void showSetPwdDialog() {
        DialogUtility.showDialog(SendRedToGroupActivity.this, R.string.not_set_pay_pwd, R.string.sure, R.string.cancel, true,
                new IOnBottomDialogListener() {

                    @Override
                    public void onClicked() {
                        Intent intent = new Intent(SendRedToGroupActivity.this, SetPayPwdActivity.class);
                        startActivity(intent);
                        finish();
                    }
                });
    }

    /**
     * 支付密码提示框
     *
     * @param total_money
     * @param red_count
     * @param content
     */
    private void showPayPwdDialog(final String total_money, final String red_count, final String content) {
        PayPwdDialog.showBottomRedDialog(SendRedToGroupActivity.this, new PayPwdDialog.IPayPwdInputFinishListener() {

            @Override
            public void onPayPwdInputFinish(String payPwd) {
                createRed(total_money, red_count, content, payPwd);
            }
        });
    }

    private void checkRecharge() {
        String money = red_total_money_et.getText().toString();
        if (!TextUtils.isEmpty(money)) {
            EditTextUtils.inputDecimal(red_total_money_et, red_total_money_et.getText().toString());
            total_moeny_tv.setText("¥" + red_total_money_et.getText().toString());
        }
    }

    private void checkBtnStatus() {
        String money = red_total_money_et.getText().toString();
        String count = red_count_et.getText().toString();
        if (!TextUtils.isEmpty(money) && !TextUtils.isEmpty(count)) {
            send_btn.setEnabled(true);
            send_btn.setBackgroundResource(R.drawable.received_red_dialog_btn_selector);
        } else {
            send_btn.setEnabled(false);
            send_btn.setBackgroundResource(R.drawable.btn_open_red_shape_bg_uncheck);
        }
    }

    private void updateRedStatus() {
        if (red_type == 1) {
            update_red_status_tv.setText(getResources().getString(R.string.red_update_red_type_luck));
            red_status_tv.setText(getResources().getString(R.string.red_now_red_type_ordinary));
            red_total_tv.setText(getResources().getString(R.string.red_one_money));
            setTotalMoney();
            red_type = 2;
        } else {
            update_red_status_tv.setText(getResources().getString(R.string.red_update_red_type_ordinary));
            red_status_tv.setText(getResources().getString(R.string.red_now_red_type_luck));
            red_total_tv.setText(getResources().getString(R.string.red_total_money));
            String money = red_total_money_et.getText().toString();
            if (!TextUtils.isEmpty(money)) {
                total_moeny_tv.setText("¥" + money);
            }
            red_type = 1;
        }
    }

    private void setTotalMoney() {
        String count = red_count_et.getText().toString();
        String money = red_total_money_et.getText().toString();
        try {
            int redCount = Integer.valueOf(count);
            double sigleMoney = Double.valueOf(money);
            double total = 0.00;
            if (redCount > 0) {
                total = redCount * sigleMoney;
            }
            if (total > 0) {
                BigDecimal b = new BigDecimal(total);
                double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                total_moeny_tv.setText("¥" + f1);
            } else {
                total_moeny_tv.setText("¥0.00");
            }
        } catch (Exception e) {
            total_moeny_tv.setText("¥0.00");
        }
    }

    private void createRed(String amount, String number, String blessing, String paypassword) {
        loading.setVisibility(View.VISIBLE);
        mRedHandler.createRed(amount, number, red_type, blessing, paypassword, new RedHandler.ICreateRedListener() {

            @Override
            public void onCreateRedResult(String packetsid, int status, String msg) {
                if (status == HttpInvokeResultCode.RESULT_OK) {
                    if (TextUtils.isEmpty(chat_id)) {
                        chooseContacts(packetsid);
                    } else {
                        sendRed(packetsid);
                    }
                } else if (status == 2605) {
                    loading.setVisibility(View.GONE);
                    // TODO 提示余额不足是否立即充值
                    showInsufficientBalanceDialog();
                } else {
                    loading.setVisibility(View.GONE);
                    IMApplication.showToast(msg);
                }
            }
        });
    }

    private void sendRed(final String packetsid) {
        mRedHandler.sendRed(packetsid, chat_id, 2, new RedHandler.ISendRedResult() {

            @Override
            public void onSendResult(int status, String reason) {
                loading.setVisibility(View.GONE);
                if (status == HttpInvokeResultCode.RESULT_OK)
                    sendRedToTalk(packetsid);
                else if (status == 2605) {
                    showInsufficientBalanceDialog();
                    // IMApplication.showToast(reason);
                }
            }
        });
    }

    private void sendRedToTalk(String packetsid) {
        String content = getResources().getString(R.string.red_default_content);
        String red_content = red_content_et.getText().toString();
        if (!TextUtils.isEmpty(red_content)) {
            content = red_content;
        }
        Intent intent = new Intent();
        intent.putExtra("packetsid", packetsid);
        intent.putExtra("content", content);
        setResult(RESULT_OK, intent);
        Utils.hideSoftKeyboard(red_total_money_et);
        Utils.hideSoftKeyboard(red_content_et);
        sendBroadcast(new Intent("balance_change"));
        finish();
    }

    private void chooseContacts(String packetsid) {
        String content = getResources().getString(R.string.red_default_content);
        String red_content = red_content_et.getText().toString();
        if (!TextUtils.isEmpty(red_content)) {
            content = red_content;
        }
        MsgRedModel msgRedModel = new MsgRedModel();
        msgRedModel.setContent(content);
        msgRedModel.setPacketsid(packetsid);
        Bundle bundle = new Bundle();
        bundle.putParcelable("forwardMsg", msgRedModel);
        Utils.startActivityForResult(SendRedToGroupActivity.this, PickTalkActivity.class, bundle, 100);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 100 && resultCode == RESULT_OK) {
            setResult(RESULT_OK);
            finish();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void getMyBalance() {
        WalletHandle.getBalance(new WalletHandle.IGetBalanceResultListener() {

            @Override
            public void onGetBalanceResult(String balance, int status, int _haspaypassword) {
                if (status == HttpInvokeResultCode.RESULT_OK) {
                    if (!TextUtils.isEmpty(balance)) {
                        myBalance = Double.valueOf(balance);
                    }
                    haspaypassword = _haspaypassword;
                }
            }
        });
    }

    private void showInsufficientBalanceDialog() {
        DialogUtility.showDialog(SendRedToGroupActivity.this, R.string.insufficient_balance, R.string.sure, R.string.cancel, true,
                new IOnBottomDialogListener() {

                    @Override
                    public void onClicked() {
                        Intent intent = new Intent(SendRedToGroupActivity.this, ChargeActivity.class);
                        startActivityForResult(intent, 100);
                    }
                });
    }
}
